﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace WpfCheckListBox
{
    /// <summary>
    /// Interaction logic for CheckedListBox.xaml
    /// </summary>
    public partial class CheckedListBox
    {
        public CheckedListBox()
        {
            InitializeComponent();
        }

        public ListBox ListBox
        {
            get { return listBox; }
        }

        private void CheckBoxChecked(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateSelectedValue();
            if (SelectedItemChanged != null)
            {
                SelectedItemChanged(sender, e);
            }
        }

        private void UpdateSelectedValue()
        {
            var checkedListItems = listBox.ItemsSource as ObservableCollection<CheckedListBoxItem>;
            if (checkedListItems != null)
            {
                SelectedValues = new List<string>();
                foreach (CheckedListBoxItem item in checkedListItems)
                {
                    if (item.IsChecked)
                    {
                        SelectedValues.Add(item.ValueMember);
                    }
                }
            }
        }

        private void CheckBoxUnchecked(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateSelectedValue();
            if (SelectedItemChanged != null)
            {
                SelectedItemChanged(sender, e);
            }
        }

        public List<string> SelectedValues { get; private set; }

        public event EventHandler SelectedItemChanged;
    }
}
